{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Python模块和包\n",
    "\n",
    "## 课程介绍\n",
    "\n",
    "欢迎来到Python模块和包的学习课程！在前面的课程中，我们已经学习了Python的基础语法、数据类型、控制流程、函数和类。现在，我们将学习如何通过使用模块和包来组织和复用代码。\n",
    "\n",
    "### 学习目标\n",
    "- 理解什么是模块和包\n",
    "- 学习如何导入和使用模块\n",
    "- 熟悉Python常用标准库\n",
    "- 掌握如何安装和使用第三方库\n",
    "\n",
    "让我们开始吧！"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. 什么是模块和包？\n",
    "\n",
    "### 1.1 模块 (Module)\n",
    "\n",
    "**模块**是一个包含Python定义和语句的文件。文件名就是模块名加上`.py`后缀。例如，一个名为`hello.py`的文件就是一个名为`hello`的模块。\n",
    "\n",
    "模块的作用：\n",
    "- 组织相关的代码\n",
    "- 避免命名冲突\n",
    "- 提高代码的可重用性\n",
    "\n",
    "### 1.2 包 (Package)\n",
    "\n",
    "**包**是一种特殊的模块，它包含一组相关的模块。在文件系统中，包是一个包含多个模块文件和一个特殊的`__init__.py`文件的目录。\n",
    "\n",
    "包的作用：\n",
    "- 进一步组织模块\n",
    "- 提供命名空间，避免模块名冲突\n",
    "- 方便分发和安装"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. 导入和使用模块\n",
    "\n",
    "Python提供了多种方式来导入模块："
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.1 导入整个模块"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 导入整个模块\n",
    "import math\n",
    "\n",
    "# 使用模块中的函数或变量\n",
    "radius = 5\n",
    "area = math.pi * radius**2\n",
    "print(f\"圆的面积: {area:.2f}\")\n",
    "\n",
    "# 使用模块中的函数\n",
    "print(f\"2的平方根: {math.sqrt(2):.4f}\")\n",
    "print(f\"向上取整9.2: {math.ceil(9.2)}\")\n",
    "print(f\"向下取整9.2: {math.floor(9.2)}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.2 导入特定的函数或变量"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 只导入需要的函数或变量\n",
    "from math import pi, sqrt\n",
    "\n",
    "# 直接使用导入的函数或变量，不需要模块名前缀\n",
    "radius = 5\n",
    "area = pi * radius**2\n",
    "print(f\"圆的面积: {area:.2f}\")\n",
    "print(f\"2的平方根: {sqrt(2):.4f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.3 导入模块并使用别名"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 给模块起个简短的别名\n",
    "import math as m\n",
    "\n",
    "# 使用别名访问模块中的内容\n",
    "print(f\"圆周率: {m.pi:.6f}\")\n",
    "print(f\"5的阶乘: {m.factorial(5)}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.4 导入模块中的所有内容"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 导入模块中的所有内容（通常不推荐，因为可能导致命名冲突）\n",
    "from math import *\n",
    "\n",
    "# 直接使用函数名\n",
    "print(f\"圆周率: {pi:.6f}\")\n",
    "print(f\"自然对数的底: {e:.6f}\")\n",
    "print(f\"45度的正弦值: {sin(radians(45)):.4f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.5 使用from...import...as...语法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 导入特定函数并起别名\n",
    "from math import sqrt as square_root\n",
    "\n",
    "# 使用别名\n",
    "print(f\"16的平方根: {square_root(16)}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.6 导入包中的模块"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 导入包中的模块\n",
    "import os.path\n",
    "\n",
    "# 使用模块中的函数\n",
    "print(f\"当前文件的绝对路径: {os.path.abspath('.')}\")  # `.` 表示当前目录\n",
    "print(f\"当前文件是否存在: {os.path.exists('.')}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.7 导入注意事项\n",
    "\n",
    "1. **导入顺序**：习惯上，导入语句应该放在文件的开头\n",
    "2. **避免循环导入**：两个模块不应该相互导入对方\n",
    "3. **避免使用 `from module import *`**：这可能导致命名冲突\n",
    "4. **使用相对导入**：在包内的模块之间可以使用相对导入（如 `from . import module`）"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. 常用标准库介绍\n",
    "\n",
    "Python自带了许多有用的标准库模块，这些模块已经安装在Python中，可以直接导入使用。让我们来看看一些常用的标准库："
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.1 datetime 模块 — 日期和时间处理"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import datetime\n",
    "\n",
    "# 获取当前日期和时间\n",
    "now = datetime.datetime.now()\n",
    "print(f\"当前日期和时间: {now}\")\n",
    "\n",
    "# 获取当前日期\n",
    "today = datetime.date.today()\n",
    "print(f\"今天的日期: {today}\")\n",
    "\n",
    "# 创建特定日期\n",
    "new_year = datetime.date(2023, 1, 1)\n",
    "print(f\"2023年元旦: {new_year}\")\n",
    "\n",
    "# 日期格式化\n",
    "print(f\"格式化日期: {now.strftime('%Y年%m月%d日 %H:%M:%S')}\")\n",
    "\n",
    "# 日期计算\n",
    "one_week_later = today + datetime.timedelta(days=7)\n",
    "print(f\"一周后的日期: {one_week_later}\")\n",
    "\n",
    "# 解析日期字符串\n",
    "date_string = \"2023-05-15\"\n",
    "parsed_date = datetime.datetime.strptime(date_string, \"%Y-%m-%d\")\n",
    "print(f\"解析后的日期: {parsed_date}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.2 random 模块 — 生成随机数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import random\n",
    "\n",
    "# 生成0到1之间的随机浮点数\n",
    "print(f\"随机浮点数: {random.random()}\")\n",
    "\n",
    "# 生成指定范围内的随机整数\n",
    "print(f\"1到100之间的随机整数: {random.randint(1, 100)}\")\n",
    "\n",
    "# 从序列中随机选择元素\n",
    "fruits = [\"苹果\", \"香蕉\", \"橙子\", \"葡萄\", \"西瓜\"]\n",
    "print(f\"随机选择的水果: {random.choice(fruits)}\")\n",
    "\n",
    "# 随机打乱序列\n",
    "numbers = [1, 2, 3, 4, 5]\n",
    "random.shuffle(numbers)\n",
    "print(f\"打乱后的序列: {numbers}\")\n",
    "\n",
    "# 从序列中随机选择多个元素（不重复）\n",
    "selected_fruits = random.sample(fruits, 3)\n",
    "print(f\"随机选择的3个水果: {selected_fruits}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.3 math 模块 — 数学函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import math\n",
    "\n",
    "# 常数\n",
    "print(f\"圆周率: {math.pi}\")\n",
    "print(f\"自然对数的底: {math.e}\")\n",
    "\n",
    "# 三角函数\n",
    "angle = math.radians(45)  # 将角度转换为弧度\n",
    "print(f\"45度的正弦值: {math.sin(angle)}\")\n",
    "print(f\"45度的余弦值: {math.cos(angle)}\")\n",
    "\n",
    "# 指数和对数\n",
    "print(f\"2的8次方: {math.pow(2, 8)}\")\n",
    "print(f\"1000的自然对数: {math.log(1000)}\")\n",
    "print(f\"1000的以10为底的对数: {math.log10(1000)}\")\n",
    "\n",
    "# 其他函数\n",
    "print(f\"5的阶乘: {math.factorial(5)}\")\n",
    "print(f\"两点之间的欧几里得距离: {math.dist([0, 0], [3, 4])}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.4 os 模块 — 操作系统接口"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "# 获取当前工作目录\n",
    "print(f\"当前工作目录: {os.getcwd()}\")\n",
    "\n",
    "# 列出目录内容\n",
    "print(f\"当前目录内容: {os.listdir('.')}\")\n",
    "\n",
    "# 检查文件或目录是否存在\n",
    "print(f\"'.'是否存在: {os.path.exists('.')}\")\n",
    "\n",
    "# 获取环境变量\n",
    "print(f\"HOME环境变量: {os.environ.get('HOME', '未设置')}\")\n",
    "\n",
    "# 路径操作\n",
    "file_path = os.path.join('folder', 'subfolder', 'file.txt')\n",
    "print(f\"拼接后的路径: {file_path}\")\n",
    "print(f\"基础文件名: {os.path.basename(file_path)}\")\n",
    "print(f\"目录名: {os.path.dirname(file_path)}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.5 sys 模块 — 系统特定参数和函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "\n",
    "# Python版本信息\n",
    "print(f\"Python版本: {sys.version}\")\n",
    "print(f\"Python版本信息: {sys.version_info}\")\n",
    "\n",
    "# 平台信息\n",
    "print(f\"操作系统平台: {sys.platform}\")\n",
    "\n",
    "# 模块搜索路径\n",
    "print(\"模块搜索路径:\")\n",
    "for path in sys.path:\n",
    "    print(f\"  - {path}\")\n",
    "\n",
    "# 获取当前引用计数\n",
    "x = \"Hello\"\n",
    "print(f\"变量x的引用计数: {sys.getrefcount(x) - 1}\")  # 减1是因为getrefcount函数本身会增加引用计数"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.6 json 模块 — JSON数据处理"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "\n",
    "# Python对象转JSON字符串\n",
    "person = {\n",
    "    \"name\": \"张三\",\n",
    "    \"age\": 30,\n",
    "    \"city\": \"北京\",\n",
    "    \"skills\": [\"Python\", \"Java\", \"JavaScript\"],\n",
    "    \"married\": False\n",
    "}\n",
    "\n",
    "json_str = json.dumps(person, ensure_ascii=False, indent=4)  # ensure_ascii=False确保中文正常显示\n",
    "print(\"JSON字符串:\")\n",
    "print(json_str)\n",
    "\n",
    "# JSON字符串转Python对象\n",
    "decoded_person = json.loads(json_str)\n",
    "print(\"\\n解码后的Python对象:\")\n",
    "print(decoded_person)\n",
    "print(f\"姓名: {decoded_person['name']}\")\n",
    "print(f\"技能: {', '.join(decoded_person['skills'])}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.7 re 模块 — 正则表达式"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import re\n",
    "\n",
    "# 正则表达式匹配示例\n",
    "text = \"我的电子邮箱是 example@email.com, 电话号码是 13812345678.\"\n",
    "\n",
    "# 提取电子邮箱\n",
    "email_pattern = r'[\\w\\.-]+@[\\w\\.-]+'\n",
    "emails = re.findall(email_pattern, text)\n",
    "print(f\"提取的电子邮箱: {emails}\")\n",
    "\n",
    "# 提取电话号码\n",
    "phone_pattern = r'1\\d{10}'\n",
    "phones = re.findall(phone_pattern, text)\n",
    "print(f\"提取的电话号码: {phones}\")\n",
    "\n",
    "# 替换文本\n",
    "censored_text = re.sub(r'(\\d{3})\\d{4}(\\d{4})', r'\\1****\\2', text)\n",
    "print(f\"隐藏部分电话号码后的文本: {censored_text}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.8 time 模块 — 时间访问和转换"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import time\n",
    "\n",
    "# 获取当前时间戳（从1970年1月1日00:00:00 UTC开始的秒数）\n",
    "current_timestamp = time.time()\n",
    "print(f\"当前时间戳: {current_timestamp}\")\n",
    "\n",
    "# 转换为本地时间\n",
    "local_time = time.localtime(current_timestamp)\n",
    "print(f\"本地时间: {local_time}\")\n",
    "\n",
    "# 格式化时间\n",
    "formatted_time = time.strftime(\"%Y-%m-%d %H:%M:%S\", local_time)\n",
    "print(f\"格式化时间: {formatted_time}\")\n",
    "\n",
    "# 休眠函数\n",
    "print(\"休眠1秒...\")\n",
    "time.sleep(1)\n",
    "print(\"继续执行\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.9 urllib 模块 — URL处理"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import urllib.request\n",
    "import urllib.parse\n",
    "\n",
    "# 构建URL\n",
    "base_url = \"https://www.example.com/search\"\n",
    "params = {\n",
    "    \"q\": \"Python教程\",\n",
    "    \"lang\": \"zh-CN\",\n",
    "    \"page\": 1\n",
    "}\n",
    "query_string = urllib.parse.urlencode(params)\n",
    "full_url = f\"{base_url}?{query_string}\"\n",
    "print(f\"完整URL: {full_url}\")\n",
    "\n",
    "# 解析URL\n",
    "parsed_url = urllib.parse.urlparse(full_url)\n",
    "print(f\"解析后的URL: {parsed_url}\")\n",
    "print(f\"域名: {parsed_url.netloc}\")\n",
    "print(f\"路径: {parsed_url.path}\")\n",
    "print(f\"查询参数: {parsed_url.query}\")\n",
    "\n",
    "# 发送请求 (注意：这里只是示例代码，并不会真正执行)\n",
    "print(\"\\n以下是发送请求的示例代码 (不会真正执行)：\")\n",
    "print(\"\"\"try:\n",
    "    response = urllib.request.urlopen('https://www.python.org')\n",
    "    html = response.read().decode('utf-8')\n",
    "    print(f\"网页标题: {html.split('<title>')[1].split('</title>')[0]}\")\n",
    "except urllib.error.URLError as e:\n",
    "    print(f\"请求失败: {e.reason}\")\n",
    "\"\"\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4. 第三方库的安装和使用\n",
    "\n",
    "除了Python标准库，还有大量的第三方库可以扩展Python的功能。我们可以使用`pip`命令来安装这些库。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 4.1 使用pip安装第三方库\n",
    "\n",
    "pip是Python的包管理器，用于安装和管理第三方库。以下是一些常用的pip命令：\n",
    "\n",
    "```bash\n",
    "# 安装包\n",
    "pip install 包名\n",
    "\n",
    "# 安装特定版本的包\n",
    "pip install 包名==版本号\n",
    "\n",
    "# 升级包\n",
    "pip install --upgrade 包名\n",
    "\n",
    "# 卸载包\n",
    "pip uninstall 包名\n",
    "\n",
    "# 列出已安装的包\n",
    "pip list\n",
    "\n",
    "# 搜索包\n",
    "pip search 关键词  # 注意：此功能在某些pip版本中可能不可用\n",
    "\n",
    "# 查看包的详细信息\n",
    "pip show 包名\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5. 总结\n",
    "\n",
    "在这节课中，我们学习了Python的模块和包，包括：\n",
    "\n",
    "1. **模块和包的概念**：\n",
    "   - 模块是包含Python定义和语句的文件\n",
    "   - 包是包含多个模块的目录\n",
    "\n",
    "2. **导入和使用模块**：\n",
    "   - `import module`\n",
    "   - `from module import function, variable`\n",
    "   - `import module as alias`\n",
    "\n",
    "3. **常用标准库**：\n",
    "   - `datetime`：日期和时间处理\n",
    "   - `random`：生成随机数\n",
    "   - `math`：数学函数\n",
    "   - `os`：操作系统接口\n",
    "   - `sys`：系统特定参数和函数\n",
    "   - `json`：JSON数据处理\n",
    "   - `re`：正则表达式\n",
    "   - `time`：时间访问和转换\n",
    "   - `urllib`：URL处理\n",
    "\n",
    "4. **第三方库的安装和使用**：\n",
    "   - 使用`pip`命令安装第三方库\n",
    "   - 常用第三方库：requests、pandas、matplotlib、NumPy、BeautifulSoup等\n",
    "\n",
    "5. **自定义模块和包**：\n",
    "   - 创建自己的模块和包来组织代码\n",
    "   - 使用`__init__.py`文件初始化包\n",
    "\n",
    "6. **实际应用**：\n",
    "   - 将多个模块和包结合使用来完成实际项目\n",
    "   - 数据生成、保存、分析和可视化的完整流程\n",
    "\n",
    "通过使用模块和包，我们可以更好地组织代码，提高代码的可重用性和可维护性，同时也可以使用丰富的第三方库来扩展Python的功能。"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
